import { createRouter, createWebHistory } from 'vue-router'
import { useAppStore } from '@/stores/app'

// 路由组件懒加载
const Home = () => import('@/views/Home.vue')
const Search = () => import('@/views/Search.vue')
const Browse = () => import('@/views/Browse.vue')
const Article = () => import('@/views/Article.vue')
const Favorites = () => import('@/views/Favorites.vue')
const Settings = () => import('@/views/Settings.vue')
const AITest = () => import('@/views/AITest.vue')

// 路由配置
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页',
      keepAlive: true,
    },
  },
  {
    path: '/search',
    name: 'Search',
    component: Search,
    meta: {
      title: '搜索',
      keepAlive: true,
    },
  },
  {
    path: '/browse',
    name: 'Browse',
    component: Browse,
    meta: {
      title: '浏览',
      keepAlive: true,
    },
  },
  {
    path: '/browse/:chapter',
    name: 'BrowseChapter',
    component: Browse,
    props: true,
    meta: {
      title: '章节浏览',
    },
  },
  {
    path: '/article/:id',
    name: 'Article',
    component: Article,
    props: true,
    meta: {
      title: '条文详情',
    },
  },
  {
    path: '/favorites',
    name: 'Favorites',
    component: Favorites,
    meta: {
      title: '我的收藏',
      keepAlive: true,
    },
  },
  {
    path: '/settings',
    name: 'Settings',
    component: Settings,
    meta: {
      title: '设置',
    },
  },
  {
    path: '/ai-test',
    name: 'AITest',
    component: AITest,
    meta: {
      title: 'AI功能测试',
    },
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    redirect: '/',
  },
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  },
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const appStore = useAppStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 民法典H5应用` : '民法典H5应用'
  
  // 清除错误状态
  appStore.clearError()
  
  next()
})

// 全局后置钩子
router.afterEach((to, from) => {
  // 页面访问统计等
  console.log(`路由跳转: ${from.path} -> ${to.path}`)
})

export default router
